export class FadeInAnimation {
  node: HTMLHeadingElement | null;
  duration: number | undefined;
  startTime: number | undefined;
  frameId: number | undefined;

  constructor(node: HTMLHeadingElement | null) {
    this.node = node;
  }
  start(duration: number) {
    this.duration = duration;
    this.onProgress(0);
    this.startTime = performance.now();
    this.frameId = requestAnimationFrame(() => this.onFrame());
  }
  onFrame() {
    const timePassed = performance.now() - (this.startTime as number);
    const progress = Math.min(timePassed / (this.duration as number), 1);
    this.onProgress(progress);
    if (progress === 1) {
      this.stop();
    } else {
      // 还有很多的帧要绘制
      this.frameId = requestAnimationFrame(() => this.onFrame());
    }
  }
  onProgress(progress: number) {
    if (this.node !== null) {
      this.node.style.opacity = progress.toString();
    }
  }
  stop() {
    cancelAnimationFrame(this.frameId as number);
    this.startTime = undefined;
    this.frameId = undefined;
    this.duration = 0;
  }
}
